package com.csh.szhm.http;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.android.volley.Request;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.csh.szhm.SzhmApplication;
import com.csh.szhm.utils.StringUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class HttpRequestTool<T> {

	private GsonRequest<T> mRequest;

	private void addRequest(Request<T> req) {
		SzhmApplication.getRequestQueue().add(req);
	}

	public GsonRequest<T> cloneRequest(int method, String url,
			TypeToken<T> toke, String activity, final String type) {
		if (!url.contains("http") && !url.contains("https")) {
			if (mCallBackUi != null) {
				mCallBackUi.success(null);
			}
			return null;
		}
		String regex = "([\u4e00-\u9fa5]+)";
		Matcher matcher = Pattern.compile(regex).matcher(url);
		StringBuffer buffer = null;
		while (matcher.find()) {
			if (buffer == null) {
				buffer = new StringBuffer();
			}
			String dd = matcher.group(0);
			try {
				dd = URLEncoder.encode(dd, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			matcher.appendReplacement(buffer, dd);
		}
		if (buffer != null) {
			url = buffer.toString();
		}
		HttpRequestManager.cencalRequest(activity, type);
		mRequest = new GsonRequest<T>(method, url, new Listener<T>() {
			@Override
			public void onResponse(T response) {
				// if (response == null) {
				// return;
				// }
				synchronized (mRequest) {
					if (mCallBackUi != null) {
						mCallBackUi.requestType(type);
					}
					if (mCallBackUi != null) {
						mCallBackUi.success(response);
					}
				}

			}
		}, new ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				synchronized (mRequest) {
					if (mCallBackUi != null) {
						mCallBackUi.requestType(type);
					}
					if (mCallBackUi != null) {
						mCallBackUi.failed(error);
					}
				}
			}
		});
		mRequest.setTypeToke(toke);
		if (!StringUtil.isEmptyString(requestBody)) {
			mRequest.setRequestString(requestBody);
		}
		mRequest.setRetryPolicy(new MyDefaultRetryPolicy());
		addRequest(mRequest);
		HttpRequestManager.put(activity, type, mRequest);
		return mRequest;
	}

	private final Gson mGson = new Gson();
	private String requestBody;

	public <E> void setBodyData(E e) {
		requestBody = mGson.toJson(e);
	}

	public void cencalRequest() {
		if (mRequest != null) {
			mRequest.cancel();
		}
	}

	private HttpCallBackUi<T> mCallBackUi;

	public void setHttpCallBackUi(HttpCallBackUi<T> cal) {
		mCallBackUi = cal;
	}
}
